package com.jsz.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jsz.constant.MessageConstant;
import com.jsz.entity.Result;
import com.jsz.service.MemberService;
import com.jsz.service.ReportService;
import com.jsz.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *数据统计管理
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;

    //会员数据折线图
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        //准备一个Map集合用来存储数据
        Map<String, Object> map = new HashMap<>();
        //准备一个List集合用来封装数据
        List<String> months = new ArrayList<>();

        //获取一个日历对象, 模拟时间就是当前时间
        Calendar calendar = Calendar.getInstance();
        //计算过去一年的的12个月
        calendar.add(Calendar.MONTH, -12);
        for (int i = 0; i < 12; i++) {
            //获得当前日期往后推一个月,当便利结束就获取到所有12个月的月份信息了 (比如当前为11月, 那么推后一个月就是12月)
            calendar.add(Calendar.MONTH, 1);
            Date date = calendar.getTime();
            //将创建的date日期类型转换成我们指定的yyyy-MM格式. 并且存放进list集合中存储
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        //讲获取到的所有月份信息带人map集合中,用于返回给前端
        map.put("months", months);

        //调用业务层查询数据
        List<Integer> memberCount = memberService.findMemberCountByMonth(months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    //套餐预约占比饼形图
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        //创建一个Map集合用来封装数据
        Map<String, Object> data = new HashMap<>();

        try {
            List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();
            data.put("setmealCount", setmealCount);

            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");//获取查询到的数据中的套餐名称
                setmealNames.add(name);
            }

            data.put("setmealNames", setmealNames);
            //调试
            //System.out.println("data = " + data);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //运营数据统计
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

    //导出Excel运营数据表格 (写数据进Excel中,并导出表格)
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            //创建一个map集合用来存放数据
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据,准备将拿到的数据写进Excel表格中
            String reportDate = (String) result.get("reportDate");//获取当前日期
            Integer todayNewMember = (Integer) result.get("todayNewMember");//新增会员数
            Integer totalMember = (Integer) result.get("totalMember");//总会员数
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");//本周新增会员数
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");//本月新增会员数
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");//今日预约数
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");//本周预约数
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");//本月预约数
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");//今日到诊数
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");//本周到诊数
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");//本月到诊数
            List<Map> hotsetmeal = (List<Map>) result.get("hotSetmeal");//热门套餐

            //获取Excel模板对象. 获取template所在的绝对路径, 后面File.separator表示动态给文件加上一个 /
            String temlateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));
            //拿到Excel表格中第一页
            XSSFSheet sheetAt = workbook.getSheetAt(0);

            //获取行数
            XSSFRow row = sheetAt.getRow(2);
            //获取当前列,并把数据写进单元格
            row.getCell(5).setCellValue(reportDate);//获取当前日期

            //获取行数
            row = sheetAt.getRow(4);
            //获取当前列,并把数据写进单元格
            row.getCell(5).setCellValue(todayNewMember);//新增会员数
            row.getCell(7).setCellValue(totalMember);//总会员数

            //获取行数
            row = sheetAt.getRow(5);
            //获取当前列,并把数据写进单元格
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            //获取行数
            row = sheetAt.getRow(7);
            //获取当前列,并把数据写进单元格
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            // 获取行数
            row = sheetAt.getRow(8);
            //获取当前列,并把数据写进单元格
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            // 获取行数
            row = sheetAt.getRow(9);
            //获取当前列,并把数据写进单元格
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (Map map : hotsetmeal) {//热门套餐
                String name = (String) map.get("name");//套餐名称
                Long setmeal_count = (Long) map.get("setmeal_count");//预约数量
                BigDecimal proportion = (BigDecimal) map.get("proportion");//占比
                String remark = (String) map.get("remark");//备注说明
                row = sheetAt.getRow(rowNum++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
                row.getCell(7).setCellValue(remark);
            }

            //通过输入流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//指定请求头文件格式
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//以附件的形式打开文件（下载）
            workbook.write(out);

            //关闭资源
            out.close();
            out.flush();
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL, null);
        }
    }

    //导出PDF运营数据表格 (写数据进PDF中,并导出表格)
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = reportService.getBusinessReportData();

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //动态获取pdf模板文件绝对磁盘路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";

            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

            //填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint =
                    JasperFillManager.fillReport(jasperPath, result,
                            new JRBeanCollectionDataSource(hotSetmeal));

            //创建输出流，用于从服务器写数据到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint, out);

            out.flush();
            out.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }
}
